﻿$.widget("LOB.ComboBoxPaging", {
    options: {
        value: "",
        url: "",
        textfield: "",
        widthfield: "",
        widthPopup:0,
        heightPopup: 300,
        valuefield: "",
        viewfield:"",
        pageSize: 50,
        IsRequired: false,
        format: "",
        linkfunction:"",
        AllowNotInList: 0
    },

    inputTemplate : null,
    buttonDropDown : null,
    PannelDropDown: null,
    PannelPaging: null,
    ContainerItem: null,
    dataSource: null,
    fristbutton: null,
    lastbutton: null,
    prevbutton: null,
    nextbutton: null,
    inputpagecurrent :null,
    inputtotalpage: null,
    refreshbutton:null,
    id: "",
    isLoading: false,
    _oldFilter: null,
    selectchange: null,
    isUserEnter:false,
    sp: null,
    modelcurrent: null,
    textExist : "",
    _filter: null,

    _create: function () {
        if (this.options.viewfield == "")
            this.options.viewfield = this.options.valuefield;
        var requiredClass = "";

        if(this.options.IsRequired)
            requiredClass = "borderRequired";

        var s = $("<span class='k-widget k-combobox k-header' style='width:100%;'></span>");

        this.sp = $("<span class='k-dropdown-wrap k-state-default " + requiredClass + "' unselectable='on' tabindex='-1'></span>");
        this.id = this.element[0].id;
        var requiredClass = "";

        var div = $("<div></div>");
        div.appendTo(this.element[0].parentElement);

        div.css('width', $(this.element[0]).css('width'));
        if (this.options.value == "")
            this.inputTemplate = $("<input name='" + this.element[0].id + "_Input' id='" + this.element[0].id + "_Input' data-bind=\"value:" + this.id + "\" class='lv-input k-input' type='text' autocomplete='off' name='cboData_input' role='combobox' aria-expanded='false' tabindex='0' aria-disabled='false' aria-readonly='false' aria-autocomplete='both' aria-owns='cboData_listbox' aria-activedescendant='cboData_option_selected' aria-busy='false' style='width: 100%;'></input>");
        else {
            $("#" + this.id).val(this.options.value);
            this.inputTemplate = $("<input name='" + this.element[0].id + "_Input' id='" + this.element[0].id + "_Input' data-bind=\"value:" + this.id + "\" value='" + this.options.value + "' class='lv-input k-input' type='text' autocomplete='off' name='cboData_input' role='combobox' aria-expanded='false' tabindex='0' aria-disabled='false' aria-readonly='false' aria-autocomplete='both' aria-owns='cboData_listbox' aria-activedescendant='cboData_option_selected' aria-busy='false' style='width: 100%;'></input>");
        }

        this.buttonDropDown = $("<span name='" + this.element[0].id + "' id='" + this.element[0].id + "_ButtonDD' class='lv-DropDown k-select' unselectable='on' tabindex='-1'><span class='lv-icon k-icon k-i-arrow-s' unselectable='on' role='button' tabindex='-1' aria-controls='cboData_listbox'></span></span>");
        
        this.inputTemplate.appendTo(this.sp);
        this.buttonDropDown.appendTo(this.sp);

        this.sp.hover($.proxy(function () {
            if(this.sp.hasClass("k-state-default"))
                this.sp.addClass("k-state-hover")
        }, this));
        this.sp.mouseleave($.proxy(function () {
            if (this.sp.hasClass("k-state-default"))
                this.sp.removeClass("k-state-hover")
        }, this));

        this.sp.appendTo(s);

        s.appendTo(div);

            
        
        this.inputTemplate.keydown($.proxy(
            function (e) {
                this._ProcessKey(e);
            }
            , this));

        var w = this.options.widthPopup;
        if ( w == 0) {
            if (this.options.widthfield != "") {
                if (this.options.widthfield.indexOf(";") > 0) {
                    w = 0;
                    var t = this.options.widthfield.split(";");
                    for (var i = 0; i < t.length; i++) {
                        w = w + parseInt(t[i]);
                    }
                }
            }
        }

        if (w < 300) w = 300;

        $("#" + this.id + "_PannelDD").remove();

        this.PannelDropDown = $('<div name="' + this.element[0].id + '" id="' + this.element[0].id + '_PannelDD" data-role="popup"></div>')
            .css('width', w)
            .css('height', this.options.heightPopup)
            .css('z-index', 11000)
            .css('position', 'fixed')
            .css('overflow', 'hidden')
            .addClass("LVPupop")
            .addClass("k-list-container")
            .addClass("k-popup")
            .addClass("k-group")
            .addClass("k-reset")
            .addClass("k-state-border-up")
            .addClass("k-animation-container")
            .appendTo("body")
            .hide();

        this.ContainerItem = $('<div tabindex="-1" class="lv-pupop"></div>')
            .css('height', this.options.heightPopup-30)
            .css('overflow', 'auto')
            .appendTo(this.PannelDropDown)

        this.PannelPaging = $('<div class="k-pager-wrap k-grid-pager k-widget lv-pupop  " data-role="pager"/>')
                        .css('height', '30')
                        .appendTo(this.PannelDropDown);

        this.fristbutton = $('<button  type="button" class="k-link k-state-disabled lv-paging" title="Go to the first page" style="width:24px;height:24px" href="#" data-page="1" tabindex="-1"><span class="k-icon k-i-seek-w lv-paging">seek-w</span></button>')
                    .appendTo(this.PannelPaging);

        this.prevbutton = $('<button  type="button" class="k-link k-state-disabled lv-paging" title="Go to the previous page" style="width:24px;height:24px" href="#" data-page="1" tabindex="-1"><span class="k-icon k-i-arrow-w lv-paging">arrow-w</span></button')
                    .appendTo(this.PannelPaging);

        this.inputpagecurrent = $('<input id = "' + this.id + '_pageCurrent" tabindex="-1" class="k-textbox k-state-disabled lv-paging"></input>');

        this.inputtotalpage = $('<span>/ 0</span>');

        var t = $('<span class="k-pager-input k-label"></span>');

        this.inputpagecurrent.appendTo(t);
        this.inputtotalpage.appendTo(t);

        t.appendTo(this.PannelPaging);

        this.nextbutton = $('<button  type="button" class="k-link k-state-disabled lv-paging" title="Go to the next page" style="width:24px;height:24px" href="#" data-page="2" tabindex="-1"><span class="k-icon k-i-arrow-e lv-paging">arrow-e</span></button>')
                            .appendTo(this.PannelPaging);

        this.lastbutton = $('<button  type="button" class="k-link k-state-disabled lv-paging" title="Go to the last page" style="width:24px;height:24px" href="#" data-page="2" tabindex="-1"><span class="k-icon k-i-seek-e lv-paging">seek-e</span></button>')
                            .appendTo(this.PannelPaging);
        var that = this;
        
        this.refreshbutton = $('<button  type="button" style="float:right;margin-right:6px" class="k-link lv-paging" title="Refresh" href="#" data-page="2" tabindex="-1"><span class="k-icon k-i-refresh lv-paging">seek-e</span></button>')
                        .click(function () { LVLinkRefresh(that.id, that.options.linkfunction, that.options.valuefield) })
                            .appendTo(this.PannelPaging);

        if (this.options.linkfunction != "") {
            $('<button  type="button" style="float:right;margin-right:6px" class="k-link lv-paging" title="Add" href="#" data-page="2" tabindex="-1"><span class="k-icon k-i-refresh lv-paging" style="background-position:-32px -64px">seek-e</span></button>')
                .click(function () { LVLinkAdd(that.id, that.options.linkfunction, that.options.valuefield) })
                .appendTo(this.PannelPaging);
        }

        this.inputpagecurrent.keydown($.proxy(
          function (e) {
              setTimeout($.proxy(function () {
                  if (!this.isLoading) {
                      if ($.isNumeric(this.inputpagecurrent.val())) {
                          this.ReadData(parseInt(this.inputpagecurrent.val()), true);
                      }
                  }
              }, this), 100);
              
          }
          , this));

        this.inputpagecurrent.focusout($.proxy(
                function () {
                    this.inputTemplate.focus();
                }
            , this));

        this.refreshbutton .click($.proxy(
            function (e) {
                this.ReadData(this.dataSource.page());
            }
            , this));


        this.fristbutton.click($.proxy(
            function (e) {
                this.ReadData(1,true);
            }
            , this));

        this.prevbutton.click($.proxy(
            function (e) {
                this.ReadData(this.dataSource.page() - 1, true);
            }
            , this));

        this.nextbutton.click($.proxy(
            function (e) {
                this.ReadData(this.dataSource.page() + 1, true);
            }
            ,this));

        this.lastbutton.click($.proxy(
            function (e) {
                this.ReadData(((this.dataSource.total() / this.options.pageSize) + 0.4).toFixed(), true);
            }
            , this));

        this.buttonDropDown.click(function (e) {
            var combo = $("#" + this.id.replace("_ButtonDD", "")).LVComboBox().data("LVComboBox");
            if (combo.enable()) {
                var p = $('.LVPupop');
                for (var i = 0; i < p.length; i++) {
                    if (p[i].id.replace('_PannelDD', '') != this.id.replace('_ButtonDD', ''))
                        $("#" + p[i].id.replace("_ButtonDD", "")).hide();
                }

                var p = this.id.replace("_ButtonDD", "_PannelDD");
                if (!$("#" + p).is(':visible')) {
                    combo.show();
                }
                else
                    combo.hide();
            }
            e.preventDefault();
        });


        $(document).click($.proxy(function (e) {
            var s = $(e.target).hasClass('lv-input');
            if (s)
            {
                var p = $('.LVPupop');
                for (var i = 0; i < p.length; i++) {
                    var n = p[i].id.replace("_ButtonDD", "_PannelDD");
                    if ($("#" + n).is(':visible'))
                    {
                        if(n.replace("_PannelDD" ,"")!=e.target.id.replace("_Input",""))
                        {
                           $("#" + n).hide();        
                        }
                    }
                }
            }

            if (!$(e.target).hasClass('lv-DropDown') && !$(e.target).hasClass('lv-icon') && !$(e.target).hasClass('lv-input') && !$(e.target).hasClass('lv-paging')) {
                if ($("#" + this.id + "_PannelDD").is(':visible'))
                    this._CheckOut();
            }

        },this));
    },

    _setOption: function (key, value) {
        this.options[key] = value;
        this._update();
    },

    _ProcessKey:function(event)
    {
        //alert(event.keyCode);
        //down
        if (event.keyCode == 40)
        {
            if (!this.IsOpen()) {
                this.show();
            }
            else {
                var s = this.ContainerItem.find('.k-state-selected');
                var index = -1;
                for (var i = 0; i < s.length; i++) {
                    index = i;
                }

                if (index != -1)
                {
                    var indexselect = parseInt(s[index].id.replace(this.id + "_", ""));
                    if (indexselect < this.dataSource.data().length - 1)
                    {
                        this.SelectIndex(indexselect+1);
                    }
                }
                else if (this.dataSource.data().length > 0)
                {
                    this.SelectIndex(0);
                }
            }
            event.preventDefault();
            return;
        }
        //up
        else if (event.keyCode == 38) {
            if (this.IsOpen()) {
                var s = this.ContainerItem.find('.k-state-selected');
                var index = -1;
                for (var i = 0; i < s.length; i++) {
                    index = i;
                }

                if (index != -1) {
                    var indexselect = parseInt(s[index].id.replace(this.id + "_", ""));
                    if (indexselect >0) {
                        this.SelectIndex(indexselect - 1);
                    }
                }
            }
            event.preventDefault();
            return;
        }
        //ESC
        else if (event.keyCode == 27)
        {
            this.IsOpen(false);
            event.preventDefault();
            return;
        }
        //Enter
        else if (event.keyCode == 13) {
            if (this.IsOpen())
            {
                var s = this.ContainerItem.find('.k-state-selected');
                var index = -1;
                for (var i = 0; i < s.length; i++) {
                    index = i;
                }

                if (index != -1) {
                    var indexselect = parseInt(s[index].id.replace(this.id + "_", ""));
                    this.SelectIndex(indexselect, true);
                }
                
            }
            this.IsOpen(false);
            this.inputTemplate.focus();
            event.preventDefault();
            return;
        }
        //tab
        else if (event.keyCode == 9) {
            this._CheckOut();
            //event.preventDefault();
            return;
        }

        if (event.keyCode != 16 && event.keyCode != 9) {
            setTimeout($.proxy(function () {
                if (!this.isLoading) {
                    this.isUserEnter = true;
                    if (!this.show())
                        this.ReadData(1);
                }
            }, this), 100);
        }
    },

    _CheckOut: function () {
        if (this.inputTemplate.val() == "" && $("#" + this.id).val() != "") {
            this.modelcurrent = null;
            if (this.selectchange != null)
                this.selectchange($("#" + this.id).val(), "", null);

            $("#" + this.id).trigger("change", null);
            $("#" + this.id).val("");
        }
        else if (this.isUserEnter) {
            var Exist = false;
            var data = this.dataSource.data();
            if (data != null) {
                for (var i = 0; i < data.length; i++) {
                    if (this.inputTemplate.val().toLowerCase() == data[i][this.options.viewfield].toLowerCase()) {
                        this.modelcurrent = data[i];

                        this.inputTemplate.val(data[i][this.options.viewfield]);

                        var old = $("#" + this.id).val();
                        if (old == "") {

                            if (this.selectchange != null)
                                this.selectchange("", data[i][this.options.valuefield], this.modelcurrent);

                            $("#" + this.id).trigger("change", null);
                        }
                        else {
                            for (var j = 0; j < data.length; j++) {
                                if (old == data[j][this.options.valuefield]) {
                                    if (i != j) {

                                        if (this.selectchange != null)
                                            this.selectchange(data[j][this.options.valuefield], data[i][this.options.valuefield], this.modelcurrent);

                                        $("#" + this.id).trigger("change", null);
                                    }
                                }
                            }
                        }

                        $("#" + this.id).val(this.dataSource.data()[i][this.options.valuefield]);
                        Exist = true;
                    }
                }
            }

            if (!Exist && this.options.AllowNotInList == 0) {
                this.inputTemplate.val("");

                if ($("#" + this.id).val() != "") {
                    this.modelcurrent = null;
                    if (this.selectchange != null)
                        this.selectchange($("#" + this.id).val(), "", null);

                    $("#" + this.id).trigger("change", null);
                }

                $("#" + this.id).val("");
            }
            else if (!Exist && this.options.AllowNotInList != 0) {
                $("#" + this.id).val(this.inputTemplate.val());
            }
        }

        this.IsOpen(false);
    },
    _update: function () {
        
    },

    InputControl:function()
    {
        return this.inputTemplate;
    },

    IsOpen:function(open)
    {
        var p = this.id + "_PannelDD";
        if (open === null || typeof open == "undefined") {
            return $("#" + p).is(':visible');
        }
        else {
            if (open)
            {
                this.show();
            }
            else
            {
                this.hide();
            }
        }
    },

    SelectIndex:function(index)
    {
        var s = this.ContainerItem.find('.k-state-selected');
        for (var i = 0; i < s.length; i++) {
            $(s[i]).removeClass("k-state-selected");
        }

        if (index != -1) {
            $('#' + this.id + "_" + index).addClass("k-state-selected");
            this.scrollToSelect();
        }

        if (index >= 0) {
            
            var old = this.inputTemplate.val();
            this.modelcurrent = this.dataSource.data()[index];

            this.inputTemplate.val(this.modelcurrent[this.options.viewfield]);

            if (this.selectchange != null)
                this.selectchange(old, this.modelcurrent[this.options.valuefield], this.modelcurrent);

            $("#" + this.id).val(this.modelcurrent[this.options.valuefield]);

        }
        else {
            var old = this.inputTemplate.val();
            this.modelcurrent = null;
            this.inputTemplate.val("");

            if (this.selectchange != null)
                this.selectchange(old, "", null);

            $("#" + this.id).val("");
        }
        $("#" + this.id).trigger("change", null);
        
    },

    value:function(value,text)
    {
        if (typeof value == "undefined")
        {
            return $("#" + this.id).val();

        }

        $("#" + this.id).val(value);

        if (typeof text == "undefined")
            text = value;

        this.inputTemplate.val(text);
    },

    CurentModel:function()
    {
        return this.modelcurrent;
    },

    destroy: function () {
        // Call the base destroy function.
        this._CheckOut();
        setTimeout($.proxy(function () {
            $("#" + this.id + "_PannelDD").remove();
        }, this), 100);
        
        $.Widget.prototype.destroy.call(this);
        
    },

    focus:function()
    {
        this.inputTemplate.focus();
    },
    
    enable:function(isable)
    {
        if (typeof isable == "undefined")
        {
            
            return this.sp.hasClass("k-state-default");
        }

        if (isable)
        {
            this.inputTemplate.removeAttr("disabled", "disabled");
            this.sp.addClass("k-state-default");
            this.sp.removeClass("k-state-disabled");
        }
        else
        {
            this.inputTemplate.attr("disabled", "disabled");
            this.sp.addClass("k-state-disabled");
            this.sp.removeClass("k-state-default");
        }
    },

    show: function (isNotfiltertext)
    {
        var IsRead = false;
        if (this.dataSource == null) {
            this.dataSource = new kendo.data.DataSource({
                transport: {
                    read: {
                        url: this.options.url,
                        dataType: "json",
                    }
                },
                serverPaging: true,
                serverFiltering: true,
                serverSorting: true,
                filter : { field: "[Predicates", operator: "startswith", value: "Value" },
                requestEnd: $.proxy(this.onrequestEnd,this),
                requestStart: function(e) {
                    console.log("request started");
                },
                schema: {
                    data:"Data",
                    total: "Total" // total is returned in the "total" field of the response
                },

                change: this.onchange
            });

            this.dataSource.bind("error", function (e)
            {
            });

            this.ReadData(1, true);
            IsRead = true;
        }

        $("#" + this.id + "_Input").focus();

        var offset = this._position();

        $("#" + this.id + "_PannelDD").css({ top: offset.top });
        $("#" + this.id + "_PannelDD").css({ left: offset.left });

        $("#" + this.id + "_PannelDD").show();

        this.scrollToSelect();
        return IsRead;
    },

    _position:function()
    {
        var offset = $("#" + this.id + "_Input").offset();

        var hi = $("#" + this.id + "_Input").outerHeight();
        var h = $(window).height();
        var hd = $("#" + this.id + "_PannelDD").height();

        offset.top = offset.top + hi;

        if (h - offset.top < hd)
        {
            offset.top = offset.top - hi - hd;
        }

        
        var w = $(window).width();
        var wd = $("#" + this.id + "_PannelDD").width();

        if (w - offset.left < wd)
        {
            offset.left = offset.left - (wd - (w - offset.left));
        }
        return offset;
    },

    scrollToSelect : function()
    {
        var top = 0;
        var element = null;
        var s = this.ContainerItem.find('.k-state-selected');
        for (var i = 0; i < s.length; i++) {
            element = $(s[i]);
            break;
        }

        var parent = this.ContainerItem;

        if (element == null) return;
        //$(parent)[0].scrollIntoView(true);


        //$(parent).animate({ scrollTop: $(parent).scrollTop() + $(element).offset().top - $(parent).offset().top }, 0);


        var ul = parent[0],
            itemOffsetTop = element[0].offsetTop,
            itemOffsetHeight = element[0].offsetHeight,
            ulScrollTop = ul.scrollTop,
            ulOffsetHeight = ul.clientHeight,
            bottomDistance = itemOffsetTop + itemOffsetHeight;

        ul.scrollTop = ulScrollTop > itemOffsetTop ?
            itemOffsetTop : bottomDistance > (ulScrollTop + ulOffsetHeight) ?
                       bottomDistance - ulOffsetHeight : ulScrollTop;

    },

    hide: function ()
    {
        var p = this.id + "_PannelDD";
        $("#" + p).hide();
        this.inputTemplate.focus();
    },

    onrequestEnd:function(e)
    {
        this.ContainerItem.empty();
        var table = $('<ul tabindex="-1" class="k-list k-reset lv-pupop" unselectable="on" aria-hidden="true" aria-live="polite" role="listbox"></ul>');

        if (typeof e.response == "undefined") return;

        var text = this.inputTemplate.val();

        var mulColumn = (this.options.textfield.indexOf(";") > 0);
        var fs = this.options.textfield.split(";");
        var t = this.options.widthfield.split(";");
        var fm = this.options.format.split("|");

        for (var i = 0; i < e.response.Data.length; i++) {
            var s = null;
            var iHTML = "";
            if (mulColumn) {
                
                var temp = "<table>";
                temp = temp + "<tr>";
                for (var j = 0; j < fs.length; j++) {
                    var align = "";
                    var number = false;
                    if (fm.length > j )
                    {
                        if (fm[j].toLowerCase() == "d")
                        {
                        }
                        else if(fm[j].indexOf('#')>=0)
                        {
                            number = true;
                            align = 'style="text-align: right"';
                        }
                    }
                    if (t[j] != '0') {
                        temp = temp + '<td class="lv-pupop" width="' + t[j] + 'px" ' + align + '>';
                        if (number)
                            temp = temp + kendo.toString(e.response.Data[i][$.trim(fs[j])], fm[j]);
                        else
                            temp = temp + e.response.Data[i][$.trim(fs[j])];
                        temp = temp + "</td>";
                    }
                }
                temp = temp + "</tr>";
                temp = temp + "</table>";
                iHTML = temp;
            }
            else
                iHTML = e.response.Data[i][this.options.textfield];

            if (text.toLowerCase() == e.response.Data[i][this.options.viewfield].toLowerCase())
            {
                this.textExist = e.response.Data[i][this.options.viewfield];
            }

            s = $('<li id="' + this.id + '_' + i + '" class="k-item" style="padding:0px">' + iHTML + '</li>');

            s.hover(function () { $(this).addClass("k-state-hover") });
            s.mouseleave(function () { $(this).removeClass("k-state-hover") });

            s.click($.proxy(function (e) {
                var index = e.target.id.replace(this.id + "_", "");

                if (!index && e.target.parentElement.parentElement.parentElement.parentElement.id!="") {
                    index = e.target.parentElement.parentElement.parentElement.parentElement.id.replace(this.id + "_", "");
                }

                if (index) {
                    this.SelectIndex(parseInt(index), true);
                    
                    this.hide();
                }
                e.preventDefault();
            }, this));

            s.appendTo(table);
        }

        table.appendTo(this.ContainerItem);
        this.inputpagecurrent.val(this.dataSource.page());

        var p = ((e.response.Total / this.options.pageSize) + 0.4);
        p = p.toFixed();
        this.inputtotalpage[0].innerHTML = '/ ' + p;

        if (p !=0 && (this.dataSource.page() != 0 && p != 1)) {
            this.inputpagecurrent.removeClass("k-state-disabled");
            this.inputpagecurrent.removeAttr("disabled", "disabled");
        }
        else {
            this.inputpagecurrent.attr("disabled", "disabled");
            this.inputpagecurrent.addClass("k-state-disabled");
        }


        if (p == 0 || this.dataSource.page() == 1 || this.dataSource.page() == 0) {
            this.fristbutton.attr("disabled", "disabled");
            this.prevbutton.attr("disabled", "disabled");
            this.fristbutton.addClass("k-state-disabled")
            this.prevbutton.addClass("k-state-disabled")
        }
        else {
            this.fristbutton.removeAttr("disabled", "disabled");
            this.prevbutton.removeAttr("disabled", "disabled");
            this.fristbutton.removeClass("k-state-disabled");
            this.prevbutton.removeClass("k-state-disabled");
        }

        if (p==0 || this.dataSource.page() == p || this.dataSource.page() == 0) {
            this.lastbutton.attr("disabled", "disabled");
            this.nextbutton.attr("disabled", "disabled");
            this.lastbutton.addClass("k-state-disabled")
            this.nextbutton.addClass("k-state-disabled")
        }
        else {
            this.lastbutton.removeAttr("disabled", "disabled");
            this.nextbutton.removeAttr("disabled", "disabled");
            this.lastbutton.removeClass("k-state-disabled");
            this.nextbutton.removeClass("k-state-disabled");
        }

        this.isLoading = false;
    },

    onchange:function(e)
    {
    },

    ReadData:function(page,isNotfiltertext)
    {
        this.isLoading = true;

        var begin = 0;
        if (this._filter != null)
        {
            begin = this._filter.field.split("~").length-1;
        }

        var text = this.inputTemplate.val();

        var Predicates = "";
        var Value = "";
        var filter = null;

        if (text != "" && (typeof isNotfiltertext == "undefined" || isNotfiltertext == false)) {
            if (this.options.textfield.indexOf(";") > 0) {
                var fs = this.options.textfield.split(";");

                for (var i = 0; i < fs.length && i<2; i++) {
                    if (i != 0) {
                        Predicates = Predicates + "||";
                        Value = Value + "|";
                    }
                    Predicates = Predicates + $.trim(fs[i]) + ".IndexOf(~" + (begin + i) + ")>=0";
                    Value = Value + text;
                }
            }
            else {
                Predicates = this.options.textfield + ".IndexOf(~" + begin + ")>=0";
                Value = text;
            }

            filter = { field: Predicates, operator: "startswith", value: Value };
            this.oldFilter = filter;
        }
        else {
            if (this.oldFilter != null && text != "")
            {
                filter = this.oldFilter;
            }
        }

        if (page < 1) page = 1;

        var p = ((this.dataSource.total() / this.options.pageSize) + 0.4);
        p = p.toFixed();
        if (page > p && p > 0) page = p;

        var _f = null;
        if (filter != null && begin != 0) {
            _f = { field: "(" + this._filter.field + ")&&(" + filter.field + ")", operator: "startswith", value: this._filter.value + "|" + filter.value };
        }
        else if (filter != null) {
            _f = filter;
        }
        else if (this._filter!=null)
        {
            _f = this._filter;
        }

        if(_f ==null)
            this.dataSource.query({
                page: page,
                pageSize: this.options.pageSize
            });
        else
            this.dataSource.query({
                page: page,
                pageSize: this.options.pageSize, 
                filter: _f,
            });
    },

    filter:function(f)
    {
        this._filter = f;
    }
});